package com.htbb.service.personalInsure.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.htbb.common.base.MappingConfig;
import com.htbb.common.base.PropertiesConfig;
import com.htbb.common.base.exception.BizException;
import com.htbb.common.util.AidCreator;
import com.htbb.common.util.CheckIdCardUtils;
import com.htbb.common.util.PasswdUtil;
import com.htbb.model.personalInsure.ReqOfIsuChk;
import com.htbb.model.personalInsure.dto.Channel;
import com.htbb.model.personalInsure.entity.CheckInfo;
import com.htbb.model.personalInsure.entity.TcAcctIsu;
import com.htbb.model.personalInsure.entity.TcOrdPayDetail;
import com.htbb.order.entity.InsureOrder;
import com.htbb.order.entity.Product;
import com.htbb.order.entity.TcIsu;
import com.htbb.order.entity.TcIsuEx;
import com.htbb.order.entity.TcOrder;
import com.htbb.order.enums.IsuStatus;
import com.htbb.order.enums.OrderStatus;
import com.htbb.order.interfaces.TcIsuService;
import com.htbb.order.interfaces.TcOrderService;
import com.htbb.order.utils.DateUtil;
import com.htbb.product.interfaces.SysProductService;
import com.htbb.service.personalInsure.IsuBizService;
import com.htbb.user.entity.UcUser;
import com.htbb.user.interfaces.UcUserService;

@Service
public class IsuBizServiceImpl implements IsuBizService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private TcOrderService tcOrderService;
	@Autowired
	private TcIsuService tcIsuService;
	@Autowired
	private UcUserService ucUserService;
	@Autowired
	private SysProductService sysProductService;
	
	@Autowired
	private QHTZXPolicyService qhtzxPolicyServiceImpl;
	
	/**
	 * 投保服务
	 * @param reqOfIsuChk
	 * @return 
	 * @throws ParseException 
	 */
	@Override
	public Object commitOrder(ReqOfIsuChk reqOfIsuChk) throws Exception{
		Map<String, Object> retMap = new HashMap<String, Object>();
		
		Channel channel = MappingConfig.getChannel(reqOfIsuChk.getPartnerCode());
		/***核验信息***/
		CheckInfo checkInfo = reqOfIsuChk.check(this, channel);
		
		/***生成投保订单***/
		/*判断是否重复投保*/
		if("1".equals(checkInfo.getMaxInsured())){
			boolean isBuy = tcOrderService.isRepeatInsurance(checkInfo.getIsuSsn(), checkInfo.getProid(),checkInfo.getIsuDtStart(),checkInfo.getIsuDtEnd());
			if(isBuy){
				throw new BizException("该用户已经购买过此类产品，请勿重复购买");
			}
		}
		/*静默注册*/
		if("1".equals(checkInfo.getIsResgister())){
			this.registerUser(checkInfo);
		}else{ //用户未注册，则存为ordAid
			checkInfo.setCustAid(checkInfo.getOrderAid());
		}
		
		/*查询产品名称*/
		String prodName = sysProductService.getProductDetail(Long.parseLong(checkInfo.getProid())).getProdName();
		checkInfo.setProdName(prodName);
		
		TcOrder entity = new TcOrder();
		entity.setChannelTradeId(checkInfo.getChannelTradeId());
		TcOrder tcOrder =  tcOrderService.selectByOther(entity);
		if(tcOrder != null){
			String isuId = tcIsuService.getIsuIdByOrderId(tcOrder.getOrderId());
			TcIsu tcIsu = tcIsuService.getTcIsuDetail(isuId);
			retMap.put("status", channel.getIsautopay().equals("1") ? "1":"0");
			retMap.put("money", tcIsu.getIsuAmt());
			retMap.put("hbCode", isuId);
			return retMap;
		}
		//保存订单
		TcIsu tcIsu = this.saveCommonOrder(reqOfIsuChk,checkInfo,channel);
		
		retMap.put("status", channel.getIsautopay().equals("1") ? "1":"0");
		retMap.put("money", tcIsu.getIsuAmt());
		retMap.put("hbCode", tcIsu.getIsuId());
		return retMap;
	}
	
	/**
	 * 保存订单
	 * @param checkInfo
	 * @param channel
	 */
	private TcIsu saveCommonOrder(ReqOfIsuChk reqOfIsuChk,CheckInfo checkInfo, Channel channel) {
		Date now = new Date();
		TcOrder tcOrder = new TcOrder();
		tcOrder.setOrderId(checkInfo.getOrderAid());
		tcOrder.setOrderDate(now);
		if(!StringUtils.isEmpty(channel.getIsautopay()) && channel.getIsautopay().equals("1")){
			tcOrder.setOrderStatus(OrderStatus.COMPLETED.getValue());
		}else{
			tcOrder.setOrderStatus(OrderStatus.WAITING_FOR_PAYMENT.getValue());
		}
		
		Map<String, Product> productMap = channel.getProductMap();
		Product product = productMap.get(reqOfIsuChk.getProdType().toUpperCase());
		
		tcOrder.setOrderPhone(checkInfo.getCustPhone());
		tcOrder.setUserId(checkInfo.getCustAid());
		tcOrder.setUserName(checkInfo.getCustName());
		tcOrder.setProdId(checkInfo.getProid());
		tcOrder.setProdName(checkInfo.getProdName());
		tcOrder.setSkuId(checkInfo.getSkuid());
		tcOrder.setSkuName(product.getSkuname());
		tcOrder.setProdType(product.getProdType());
		tcOrder.setProdCode(reqOfIsuChk.getProdType());
		tcOrder.setSkuAmt(Integer.parseInt(product.getAmt()));
		tcOrder.setOrderQty(1);
		tcOrder.setOrderAmt(tcOrder.getSkuAmt());
		tcOrder.setCouponAmt("0");
		tcOrder.setPoint(0);
		tcOrder.setPartnerName(channel.getName()); //订单渠道
		tcOrder.setPartnerId(channel.getPartnerId()); //渠道id
		tcOrder.setGroupName(channel.getName()); //订单总渠道
		tcOrder.setSettlePartnerId(channel.getPartnerId()); //结算渠道编码
		tcOrder.setSettlePartnerName(channel.getName()); //结算渠道名称
		tcOrder.setSettleGroupName(channel.getName()); //订单结算总渠道
		
		TcIsu tcIsu = new TcIsu();
		String isuId = String.valueOf(PropertiesConfig.iDCreator.nextId());
		tcIsu.setIsuId(isuId);
		tcIsu.setOrderId(tcOrder.getOrderId());
		tcIsu.setUserId(tcOrder.getUserId());
		tcIsu.setUserName(tcOrder.getUserName());
		tcIsu.setProdId(tcOrder.getProdId());
		tcIsu.setProdName(tcOrder.getProdName());
		tcIsu.setSkuId(tcOrder.getSkuId());
		tcIsu.setSkuName(tcOrder.getSkuName());
		tcIsu.setProdCode(tcOrder.getProdCode());
		if(!StringUtils.isEmpty(channel.getIsautopay()) && channel.getIsautopay().equals("1")){
			tcIsu.setIsuStatus(IsuStatus.WAITING_FOR_ISSUE.getValue());
		}else{
			tcIsu.setIsuStatus(IsuStatus.WAITING_FOR_PAYMENT.getValue());
		}
		tcIsu.setIsuDate(now);
		tcIsu.setIsuAmt(Integer.parseInt(product.getSumant())); //保额
		tcIsu.setIsuFee(tcOrder.getSkuAmt());
		tcIsu.setIsuNum("");
		tcIsu.setDateStart(DateUtil.parse(checkInfo.getIsuDtStart(), DateUtil.PATTERN_CLASSICAL));
		tcIsu.setDateEnd(DateUtil.parse(checkInfo.getIsuDtEnd(), DateUtil.PATTERN_CLASSICAL));
		tcIsu.setCustName(checkInfo.getCustName());
		tcIsu.setCustPhone(checkInfo.getCustPhone());
		tcIsu.setCustSex(CheckIdCardUtils.getSexByIdCard(checkInfo.getCustSsn()));
		tcIsu.setIsuName(checkInfo.getIsuName());
		tcIsu.setIsuPhone(checkInfo.getCustPhone());
		tcIsu.setIsuIdType(checkInfo.getIsuIdType()==null?1:checkInfo.getIsuIdType());
		tcIsu.setIsuIdNum(checkInfo.getIsuSsn());
		tcIsu.setIsuBirthday(DateUtil.parse(CheckIdCardUtils.getBirthByIdCard(checkInfo.getIsuSsn()), DateUtil.PATTERN_CLASSICAL_SIMPLE));;
		tcIsu.setIsuSex(CheckIdCardUtils.getSexByIdCard(checkInfo.getIsuSsn()));
		tcIsu.setRelation(checkInfo.getCustShip());
		tcIsu.setEmail(checkInfo.getCustEmail());
		tcIsu.setVendor(product.getCompany());
		
		List<TcIsuEx> tcIsuExList = null;
		if(checkInfo.getJobType() != null && !"".equals(checkInfo.getJobType().trim())){
            tcIsuExList = new ArrayList<TcIsuEx>();
        	TcIsuEx tcIsuEx = new TcIsuEx();
        	tcIsuEx.setAid(PropertiesConfig.iDCreator.nextId()+"");
        	tcIsuEx.setIsuId(tcIsu.getIsuId());
        	tcIsuEx.setOrderId(tcOrder.getOrderId());
        	tcIsuEx.setIsuKey("工种");
        	tcIsuEx.setIsuValue(checkInfo.getJobType());
        	
        	tcIsuExList.add(tcIsuEx);
        }
		
		tcOrderService.saveCommonOrder(tcOrder, tcIsu, null, tcIsuExList);
		return tcIsu;
	}

	/**
	 * 注册用户
	 */
	@Override
	public UcUser registerUser(CheckInfo checkInfo) {
		/*先根据手机号判断用户是否已经注册，如果已经注册，则不需要再注册*/
		com.htbb.user.entity.UcUser entity = new com.htbb.user.entity.UcUser();
		entity.setPhone(checkInfo.getCustPhone());
		com.htbb.user.entity.UcUser ucUser = ucUserService.selectByOther(entity);
		if(ucUser != null){
			checkInfo.setCustAid(ucUser.getUserId());
		}else{
			String userAid = AidCreator.get() + "";
			/*取手机号码后六位作为用户密码*/
			String phoneNum = checkInfo.getCustPhone();
			String pwd = phoneNum.substring(phoneNum.length() - 6);
			checkInfo.setCustPwd(PasswdUtil.encryptPassword(pwd));
			checkInfo.setCustAid(userAid);
			checkInfo.setCustEmail(StringUtils.isEmpty(checkInfo.getCustEmail()) ? "NA" : checkInfo.getCustEmail());
			//注册用户
			ucUser = new UcUser();
			ucUser.setUserId(userAid);
			ucUser.setUserName(phoneNum);
			ucUser.setNickName(phoneNum);
			ucUser.setUserPwd(checkInfo.getCustPwd());
			ucUser.setUserLevel(1);
			ucUser.setPhone(phoneNum);
			ucUser.setEmail(checkInfo.getCustEmail());
			ucUser.setIdType(1);
			ucUser.setIdNum(checkInfo.getCustSsn());
			ucUser.setUserStatus(1);
			ucUser.setPartnerId(checkInfo.getPartnerCode());
			ucUser.setPartnerName(checkInfo.getPartnerName());
			ucUser.setGroupName(checkInfo.getPartnerName());
			ucUser.setIsDelete(0);
			ucUser.setCreateUser(checkInfo.getFpCusr());
			ucUser.setModifyUser(checkInfo.getFpMusr());
			ucUser = ucUserService.register(ucUser);
		}
		return ucUser;
	}
	
	/**
	 * 查询订单
	 */
	@Override
	public TcIsu queryTcAcctIsu(String hbCode, String orderId, String isuNum) {
		TcIsu entity = new TcIsu();
		if(hbCode != null && !hbCode.equals("")){
			entity.setIsuId(hbCode);
		}
		if(orderId != null && !orderId.equals("")){
			entity.setOrderId(orderId);
		}
		if(isuNum != null && !isuNum.equals("")){
			entity.setIsuNum(isuNum);
		}
		TcIsu tcIsu = tcIsuService.selectByOther(entity);
		return tcIsu;
	}


	@Override
	public List<InsureOrder> queryPartnerOrder(String custPhone, String partnerCode) {
		return tcIsuService.queryPartnerOrder(custPhone,partnerCode);
	}
	
	/**
	 * 停诊险退保接口
	 */
	@Override
	public Object surrender(String hbCode, String isuSsn) {
		TcIsu tcIsu = tcIsuService.getTcIsuDetail(hbCode);
		if(tcIsu == null || !tcIsu.getIsuIdNum().equals(isuSsn)){
			throw new BizException("未找到该被保身份证的投保信息！");
		}
		String resultCode = "-1";
		String resultMsg = "操作异常";
		//返回状态码字典：0退保成功 1未确认投保，无需退保 2投保处理中，需要稍后再试 -1退保失败
		String isuStatus = tcIsu.getIsuStatus()+"";
		if(isuStatus.equals("0") || isuStatus.equals("8") /*|| isuStatus.equals("9")*/){ //待支付、已取消、/*出单失败(需要记录申请退款状态)*/
			resultCode = "1";
			resultMsg = "未确认投保，无需退保";
		}
		else if(isuStatus.equals("1")){ //待出单
			resultCode = "2";
			resultMsg = "投保处理中，请稍后再试";
		}
		else if(isuStatus.equals("3") || isuStatus.equals("4")){ //已生效/已终止
			resultCode = "-1";
			resultMsg = "退保失败：已过起保时间";
		}
		else if(isuStatus.equals("10")){ //已退保
			resultCode = "0";
			resultMsg = "已退保";
		}
		else if(isuStatus.equals("2") || isuStatus.equals("9")){ //已出单  或出单失败
			/**调用保险公司退保接口【线上退保，退保成功则记录保单为已退保、订单为已申请退款】*/
			if(isuStatus.equals("2")){
				String orderTime = DateUtil.dateToString(tcIsu.getIsuDate(), DateUtil.PATTERN_CLASSICAL);
				Map<String, String> ret = qhtzxPolicyServiceImpl.sendPolicyCancellation(tcIsu.getIsuNum(), orderTime);
				if(ret.get("retCode") != null && ret.get("retCode").equals("0")){
					tcIsuService.updateIsuStatus(hbCode, IsuStatus.FINISH_FOR_ISSUE, IsuStatus.RETURN_MONEY);
					tcOrderService.updateOrderStatus(tcIsu.getOrderId(), OrderStatus.COMPLETED, OrderStatus.RETURN_MONEY);
					resultCode = "0";
					resultMsg = "退保成功";
				}
				else{
					resultCode = "-1";
					resultMsg = ret.get("retMsg");
				}
			}
			else{ //出单失败时，只更新订单状态为已申请退款
				tcOrderService.updateOrderStatus(tcIsu.getOrderId(), OrderStatus.COMPLETED, OrderStatus.RETURN_MONEY);
				resultCode = "0";
				resultMsg = "退保成功";
			}
		}
		
		Map<String, String> retMap = new HashMap<>();
		retMap.put("resultCode", resultCode);
		retMap.put("resultMsg", resultMsg);
		return retMap;
	}

}
